package cn.xspace.wnx.view.chat.chatrow;

import android.app.Activity;
import android.content.Context;
import android.util.Base64;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.util.FileUtils;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.LogUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.db.ChatFileDao;
import cn.xspace.wnx.db.ChatRecordDao;
import okhttp3.Request;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class EaseChatRowFile extends BaseChatRow {

    protected TextView fileNameView;
    protected TextView fileSizeView;
    protected TextView fileStateView;
    protected boolean isLoading;


    protected boolean isNotifyProcessed;
//    private EMNormalFileMessageBody fileMessageBody;

    public EaseChatRowFile(Context context, MsgRecordEntity message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
    }

    @Override
    protected void onInflateView() {
        inflater.inflate(!isMySend() ?
                R.layout.chat_row_received_file : R.layout.chat_row_sent_file, this);
    }

    @Override
    protected void onFindViewById() {
        fileNameView = (TextView) findViewById(R.id.tv_file_name);
        fileSizeView = (TextView) findViewById(R.id.tv_file_size);
        fileStateView = (TextView) findViewById(R.id.tv_file_state);
//        percentageView = (TextView) findViewById(R.id.percentage);
//        percentageView.setVisibility(View.GONE);
    }


    /**
     * 文件等 在上传之前需要转化
     */
    protected void file2Base64() {
        Observable convertObserv = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String content = "";
                try {
                    content = Base64.encodeToString(
                            AppUtils.readStream(new FileInputStream(message.mFileEntity.file_url_local)), 0);
                    LogUtil.d(TAG, "base 64 转换成功");
                    message.msg_content = content;
                } catch (FileNotFoundException e) {
                    LogUtil.d(TAG, "base 64 转换失败");
                    e.printStackTrace();
                    //本地 不经不存在，直接讲服务器路径发送给接口
                    message.msg_content = message.mFileEntity.file_url_remote;
                }

                subscriber.onCompleted();
            }
        });
        Subscriber<String> subscriber = new Subscriber<String>() {
            @Override
            public void onCompleted() {
                setMessageSendCallback();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(String result) {
            }
        };
        convertObserv
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }


    @Override
    protected void onSetUpView() {
//	    fileMessageBody = (EMNormalFileMessageBody) message.getBody();
//        String filePath = fileMessageBody.getLocalUrl();
        String filePath = message.mFileEntity.file_url_local;
        fileNameView.setText(message.mFileEntity.file_name);
//        fileSizeView.setText(TextFormater.getDataSize(message.mFileEntity.file_size));
        if (!isMySend()) {
            File file = new File(filePath);
            if (file.exists()) {
                message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_COMPLETE.toNumber();
                fileStateView.setText(R.string.Have_downloaded);
            } else {
                message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_NOT.toNumber();
                fileStateView.setText(R.string.Did_not_download);
            }
            return;
        } else {
            handleSendMessage();
            //我发送的文件
//            if (message.msg_send_status == MessageEntity.MsgSendStatus.NOT_SEND.toNumber()) {
//                //还没有发送，马上发送
//                file2Base64();
//                return;
//            }

        }
        // until here, to sending message

    }

    @Override
    protected void commonSendSuccessDeal(BaseReturnBean bean) {
        super.commonSendSuccessDeal(bean);
        //更新文件相关数据
    }

    @Override
    protected void commonSendFailedDeal() {
        super.commonSendFailedDeal();
    }

    @Override
    protected void commonSendBefore() {
        super.commonSendBefore();
    }

    @Override
    protected void buildSendMap() {
        super.buildSendMap();
        sendMap.put("msg_name", message.mFileEntity.file_name);
//        sendMap.put("msg_text", message.msg_content);
        File file = new File(message.mFileEntity.file_url_local);
//        if(file.exists()){
//            LogUtil.d(TAG,"文件存在");
//
//        }else {
//            LogUtil.d(TAG,"文件不存在");
//        }

    }

    /**
     * handle sending message
     */
    protected void handleSendMessage() {
        LogUtil.d(TAG, "handleSendMessage>>>");
        if (message.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
            progressBar.setVisibility(View.GONE);
            statusView.setVisibility(View.VISIBLE);
        } else if (message.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
            progressBar.setVisibility(View.GONE);
            statusView.setVisibility(View.GONE);
        } else if (/*||*/ message.msg_send_status == MessageEntity.MsgSendStatus.NOT_SEND.toNumber()) {
            progressBar.setVisibility(View.VISIBLE);
            statusView.setVisibility(View.GONE);
//            setMessageSendCallback();
            file2Base64();
            message.msg_send_status = MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber();
            registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation().updateMsgRecordSendStatus
                    (message.inserttime, MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());
            //更新正在上传的的状态
            ;
        } else if (message.msg_send_status == MessageEntity.MsgSendStatus.IN_PROGRESS.toNumber()) {
            progressBar.setVisibility(View.VISIBLE);
            statusView.setVisibility(View.GONE);
        }
//        switch (message.status()) {
//            case SUCCESS:
//                progressBar.setVisibility(View.INVISIBLE);
//                if (percentageView != null)
//                    percentageView.setVisibility(View.INVISIBLE);
//                statusView.setVisibility(View.INVISIBLE);
//                break;
//            case FAIL:
//                progressBar.setVisibility(View.INVISIBLE);
//                if (percentageView != null)
//                    percentageView.setVisibility(View.INVISIBLE);
//                statusView.setVisibility(View.VISIBLE);
//                break;
//            case INPROGRESS:
//                progressBar.setVisibility(View.VISIBLE);
//                if (percentageView != null) {
//                    percentageView.setVisibility(View.VISIBLE);
//                    percentageView.setText(message.progress() + "%");
//                }
//                statusView.setVisibility(View.INVISIBLE);
//                break;
//            default:
//                progressBar.setVisibility(View.INVISIBLE);
//                if (percentageView != null)
//                    percentageView.setVisibility(View.INVISIBLE);
//                statusView.setVisibility(View.VISIBLE);
//                break;
//        }
    }

    /**
     * 获得存放目录
     *
     * @return
     */
    protected String getSaveDir() {
        return AppConstant.FILE_ADDRESS;
    }

    /**
     * 文件下载成功
     *
     * @param result
     */
    protected void downloadSuccess(String result) {
        if (fileStateView != null)
            fileStateView.setText(context.getString(R.string.Have_downloaded));
    }

    /**
     * 文件下载失败
     */
    protected void downloadFail() {
        if (fileStateView != null) {
            fileStateView.setText(context.getString(R.string.file_download_fail));
        }

    }

    protected void getFileByHttp() {
        message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_ING.toNumber();
        OkHttpManager.getInstance().downloadAsync(message.mFileEntity.file_url_remote, getSaveDir(), "", new
                OkHttpManager.DataCallBack() {
            @Override
            public void requestBefore() {
            }

            @Override
            public void requestFailure(Request request, Exception e) {
                progressBar.setVisibility(View.INVISIBLE);
                message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_FIALED.toNumber();
//                ChatFileDao.getInstance().updateFileDownLoadStausByTime(message.inserttime, ChatFileEntity
// .DownloadStatus.DOWNLOAD_FIALED.toNumber());
                registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileDownLoadStausByTime
                        (message.inserttime, ChatFileEntity.DownloadStatus.DOWNLOAD_FIALED.toNumber())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe());
                ;

                downloadFail();
//                imageView.setImageResource(R.drawable.chat_default_image_error);
            }

            @Override
            public void requestSuccess(BaseReturnBean result) throws Exception {
            }

            @Override
            public void requestSuccess(String result) throws Exception {
                progressBar.setVisibility(View.INVISIBLE);
                message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_COMPLETE.toNumber();
//                            imageView.setImageResource();
                LogUtil.d(TAG, "本地下载路径为" + result);
                message.mFileEntity.file_url_local = result;


//                ChatFileDao.getInstance().updateFileDownLoadStausByTime(message.inserttime, ChatFileEntity
// .DownloadStatus.DOWNLOAD_COMPLETE.toNumber());

                registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileDownLoadStausByTime
                        (message.inserttime, ChatFileEntity.DownloadStatus.DOWNLOAD_FIALED.toNumber())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe());
                //更新数据库状态

                //更新本地路径
//                ChatFileDao.getInstance().updateFileLocalPath(message.inserttime, result);
                registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileLocalPath(message
                        .inserttime, result)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe());

                downloadSuccess(result);
//                showImageView(result, imageView, message.mFileEntity.file_url_remote);
            }
        });
    }

    @Override
    protected void onUpdateView() {
        super.onUpdateView();
        LogUtil.d(TAG, "onUpdateView");
    }

    @Override
    protected void onBubbleClick() {

        String filePath = message.mFileEntity.file_url_local;
        LogUtil.d(TAG, "onBubbleClick>>>>" + filePath);
        File file = new File(filePath);
        if (file.exists()) {

            // open files if it exist
            FileUtils.openFile(file, (Activity) context);
        } else {

            String localUrl = getSaveDir() + message.mFileEntity.file_name;
            File nameFile = new File(localUrl);
            if (nameFile.exists()) {
                //存在直接打开
                FileUtils.openFile(nameFile, (Activity) context);
                return;
            }
//            if (ChatFragment.isJustRecord) {
//                return;
//            }
            if (message.mFileEntity.file_download_status == ChatFileEntity.DownloadStatus.DOWNLOAD_ING.toNumber()) {
                //文件正在下载
                Toast.makeText(context, R.string.file_downloading, Toast.LENGTH_SHORT).show();
                return;
            }
            message.mFileEntity.file_download_status = ChatFileEntity.DownloadStatus.DOWNLOAD_ING.toNumber();
            registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileDownLoadStausByTime(message
                    .inserttime, ChatFileEntity.DownloadStatus.DOWNLOAD_ING.toNumber())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());
            ;

            //文件不存在了,重新下载
            progressBar.setVisibility(View.VISIBLE);
            getFileByHttp();
            // download the file
//            context.startActivity(new Intent(context, EaseShowNormalFileActivity.class).putExtra("msgbody", message
// .getBody()));

        }
//        if (message.direct() == EMMessage.Direct.RECEIVE && !message.isAcked() && message.getChatType() == ChatType
// .Chat) {
//            try {
//                EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
//            } catch (HyphenateException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }

    }
}
